package com.ericsson.enap.modules.procLog.thread;

import com.ericsson.common.pojo.FTPInfoVO;
import com.ericsson.common.util.DateUtils;
import com.ericsson.common.util.SFtpCarrierUtil;
import com.ericsson.enap.modules.procLog.entity.ImsBossKpi;
import com.ericsson.enap.modules.procLog.entity.ImsBossKpiDetail;
import com.ericsson.enap.modules.procLog.entity.ImsBossKpiItem;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.mongodb.BasicDBObject;
import com.mongodb.client.model.IndexModel;
import org.slf4j.Logger;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class ImsBossKpiThread implements Runnable{
    private Long netId;
    private FTPInfoVO ftpInfo;
    private String localPath;
    private Date date;
    private Logger log;
    private MongoTemplate mongoTemplate;
    private Integer delay;
    public ImsBossKpiThread(Long id, FTPInfoVO fTPInfoVO, String localPath, Date now, Logger log, MongoTemplate mongoTemplate, String delay) {
        this.netId=id;
        this.ftpInfo=fTPInfoVO;
        this.localPath=localPath;
        this.date=now;
        this.log=log;
        this.mongoTemplate=mongoTemplate;
        this.delay=Integer.parseInt(delay);
    }

    @Override
    public void run() {
        String beginTime = DateUtils.getStatisTime(this.delay,date,"yyyy-MM-dd_HH.mm");
        String endTime = DateUtils.getStatisTime(this.delay-5,date,"yyyy-MM-dd_HH.mm");
        String dateTime=DateUtils.getStatisTime(this.delay,date,"yyyy-MM-dd HH:mm:00");
        log.info("netId"+this.netId+"download start");
        File bossKpiFile=this.download(this.localPath,beginTime,endTime,this.log);
        log.info("netId"+this.netId+"download end");
        ImsBossKpi imsBossKpi=null;
        if(null==bossKpiFile){
            this.log.info(this.netId+"null"+"b:"+beginTime+"e:"+endTime);
        }else{
            log.info("netId"+this.netId+"analysisFile start");
            imsBossKpi =analysisFile(bossKpiFile,this.netId,dateTime);
            log.info("netId"+this.netId+"analysisFile end:"+imsBossKpi);
        }
        if(imsBossKpi!=null){
            log.info("netId"+this.netId+"insertIntoMongodb start");
            insertIntoMongodb(imsBossKpi);
            log.info("netId"+this.netId+"insertIntoMongodb end");
        }
    }

    private void insertIntoMongodb(ImsBossKpi imsBossKpi) {
        String collectionName ="imsboss_kpi";
        if(!mongoTemplate.collectionExists(collectionName)){
            List<IndexModel> indexModelList = new ArrayList<>();
            BasicDBObject index = new BasicDBObject();
            index.put("dateTime",1);
            indexModelList.add(new IndexModel(index));
            mongoTemplate.createCollection(collectionName).createIndexes(indexModelList);
        }
        mongoTemplate.insert(imsBossKpi, collectionName);
    }

    private ImsBossKpi analysisFile(File bossKpiFile,Long netId,String datetime) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(bossKpiFile));
            String tempStr;
            ImsBossKpi imsBossKpi=new ImsBossKpi();
            imsBossKpi.setNetId(netId.toString());
            imsBossKpi.setDateTime(datetime);

            Map<String, List<ImsBossKpiItem>> northbound=new HashMap<>();//key :HOSTNAME and OPERATION
            Map<String,ImsBossKpiItem> northHTemp=new HashMap<>();//HOSTNAME key :板卡
            List<ImsBossKpiItem> northO=new ArrayList<>();//OPERATION

            Map<String, List<ImsBossKpiItem>> southbound=new HashMap<>();//key :HOSTNAME and OPERATION
            Map<String,ImsBossKpiItem> southHTemp=new HashMap<>();//HOSTNAME key :板卡
            List<ImsBossKpiItem> southO=new ArrayList<>();//OPERATION

            String bound="";//标识南向；北向
            int module=0;//标识南向北向中的模块：0、事件 1、板卡 2、详细
            ImsBossKpiItem imsBossKpiItem;
            while ((tempStr = reader.readLine()) != null) {
                if(bound.equals("northbound")&&!tempStr.contains("------")){
                    module = getModule(tempStr, northHTemp, northO, module);
                }else if(bound.equals("southbound")&&!tempStr.contains("------")){
                    module = getModule(tempStr, southHTemp, southO, module);
                }

                if(tempStr.contains("northbound")&&!tempStr.contains("Failed")){
                    bound="northbound";
                    module=0;
                }else if(tempStr.contains("southbound")&&!tempStr.contains("Failed")){
                    bound="southbound";
                    module=0;
                }
            }
            reader.close();
            Collection<ImsBossKpiItem> imsBossKpiItems=northHTemp.values();
            List<ImsBossKpiItem> valueList = new ArrayList<ImsBossKpiItem>(imsBossKpiItems);
            northbound.put("hostname",valueList);
            northbound.put("operation",northO);
            imsBossKpi.setNorthbound(northbound);

            Collection<ImsBossKpiItem> imsBossKpiItemsSouth=southHTemp.values();
            List<ImsBossKpiItem> valueListSouth = new ArrayList<ImsBossKpiItem>(imsBossKpiItemsSouth);
            southbound.put("hostname",valueListSouth);
            southbound.put("operation",southO);
            imsBossKpi.setSouthbound(southbound);
            return imsBossKpi;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return null;
    }

    private static int getModule(String tempStr, Map<String, ImsBossKpiItem> temp, List<ImsBossKpiItem> temoList, int module) {
        ImsBossKpiItem imsBossKpiItem;
        ImsBossKpiDetail imsBossKpiDetail;
        if(module==0&&!tempStr.contains("z_total")&&!tempStr.contains("PL-board")){
            //System.out.println("事件："+tempStr);
            String [] result=tempStr.replaceAll("\\s+"," ").split(" ");
            if(result.length>4) {
                imsBossKpiItem = new ImsBossKpiItem();
                imsBossKpiItem.setKpi(result[0]);
                imsBossKpiItem.setAll(result[1]);
                imsBossKpiItem.setSuc(result[2]);
                imsBossKpiItem.setFail(result[3]);
                temoList.add(imsBossKpiItem);
            }
        }
        if(module==1&&!tempStr.contains("z_total")&&!tempStr.contains("PL-board")){
            //System.out.println("板卡："+tempStr);
            String [] result=tempStr.replaceAll("\\s+"," ").split(" ");
            if(result.length>4) {
                imsBossKpiItem = new ImsBossKpiItem();
                imsBossKpiItem.setKpi(result[0]);
                imsBossKpiItem.setAll(result[1]);
                imsBossKpiItem.setSuc(result[2]);
                imsBossKpiItem.setFail(result[3]);
                temp.put(result[0],imsBossKpiItem);
            }
        }
        if(module==2&&!tempStr.contains("z_total")&&!tempStr.contains("Fail")){
            //System.out.println("详细："+tempStr);
            String [] result=tempStr.replaceAll("\\s+"," ").split(" ");
            if(result.length>4) {
                imsBossKpiDetail = new ImsBossKpiDetail();
                imsBossKpiDetail.setFail(result[1]);
                imsBossKpiDetail.setEvent(result[2]);
                imsBossKpiDetail.setCode(result[3]);
                StringBuilder sb=new StringBuilder();
                for(int i=4;i<result.length;i++){
                    sb.append(result[i]).append(" ");
                }
                imsBossKpiDetail.setDesc(sb.toString());
                if(temp.containsKey(result[0])){
                    if(null==temp.get(result[0]).getDetail()){
                        List<ImsBossKpiDetail> imsBossKpiDetails=new ArrayList<>();
                        imsBossKpiDetails.add(imsBossKpiDetail);
                        temp.get(result[0]).setDetail(imsBossKpiDetails);
                    }else {
                        temp.get(result[0]).getDetail().add(imsBossKpiDetail);
                    }
                }
            }
        }
        if(tempStr.contains("PL-board")&&tempStr.contains("F_Code")){
            module=2;
        }else if(tempStr.contains("PL-board")&&tempStr.contains("All")){
            module=1;
        }
        return module;
    }

    File download(String localDir, String beginTime,String endTime, Logger log){
        File filePath = new File(localDir);
        // 删除上一批次下载的文件
        if (filePath.exists()) {
            File[] oldxmlTargetFiles = filePath.listFiles();
            for (File file : oldxmlTargetFiles) {
                if (file.exists() && file.isFile()) {
                    log.info("delete last filename"+file.getName());
                    file.delete();
                }
            }
        }

        SFtpCarrierUtil sftpCarrier = new SFtpCarrierUtil(ftpInfo, log);
        try {
            sftpCarrier.connect();
            Vector v = sftpCarrier.listFiles(ftpInfo.getPath());
            if (v.size() > 0) {
                Iterator it = v.iterator();
                while (it.hasNext()) {
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
                    String filename = entry.getFilename();
                    SftpATTRS attrs = entry.getAttrs();
                    if (!attrs.isDir()) {
                        if (filename.endsWith("_KPI.log") && filename.contains(beginTime)&& filename.contains(endTime)) {
                            File tempFile=sftpCarrier.downloadFileKpi(ftpInfo.getPath(), filename, localDir, filename);
                            log.info("netId"+this.netId+"download filename"+filename);
                            if(null!=tempFile) {
                                return tempFile;
                            }
                        }
                    }
                }
            }
        } catch (SftpException e) {
            log.error("netId"+this.netId+"SftpException:"+e.getCause());
        } finally {
            sftpCarrier.disconnect();
        }
        return null;
    }
}
